//
//  RSChatViewController.swift
//  ChatDemo
//
//  Created by 范强伟 on 2024/5/7.
//

import UIKit

let kMessageTextKey: String = "kMessageTextKey"
let kMessageImageKey: String = "kMessageImageKey"
let kMessageVoiceKey: String = "kMessageVoiceKey"

class RSChatViewController: UIViewController {

    let roomId: String
    /// 图片上传路径
    private let imageUploadPath: String = pathDocuments + "/CLChatImageUpload"
    private lazy var tableViewHepler: CLTableViewHepler = {
        let hepler = CLTableViewHepler()
        return hepler
    }()

    private lazy var tableView: CLIntrinsicTableView = {
        let tableView = CLIntrinsicTableView()
        tableView.dataSource = tableViewHepler
        tableView.delegate = tableViewHepler
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tapGestureRecognizer.delegate = self
        tapGestureRecognizer.cancelsTouchesInView = false
        tableView.addGestureRecognizer(tapGestureRecognizer)
        return tableView
    }()

    /// 输入工具条
    private lazy var inputToolBar: CLChatInputToolBar = {
        let inputToolBar = CLChatInputToolBar()
        inputToolBar.delegate = self
        inputToolBar.textFont = .mediumPingFangSC(15)
        inputToolBar.placeholder = "请输入文字..."
        return inputToolBar
    }()
    
    lazy var player: RSNetworkAudioPlayer = {
        let player = RSNetworkAudioPlayer.sharedInstance()
        player.playChangeBlock = { [weak self] obj in
            guard let weakself = self else { return }
             
            guard let cell = weakself.player.selectCell as? CLChatVoiceCell else { return  }
            cell.isPlayAnimal(obj)
        }
        return player
    }()
    
    init(roomId: String) {
        self.roomId = roomId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}

extension RSChatViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        makeConstraints()
        addTipsMessages(["欢迎"])
        getHistoryData()
    }
    
    // 读取聊天记录
    func getHistoryData(){
        if let model = RSMessageViewModel.getAllMessage(roomId){
           let list = RSMessageViewModel.chatMessageToProtocol(model)
            list?.forEach({ item in
                tableViewHepler.rows.append(item)
            })
            tableView.reloadData()
            if tableViewHepler.rows.count >= 1 {
                let item = max(tableViewHepler.rows.count - 1, 0)
                tableView.scrollToRow(at: IndexPath(item: item, section: 0), at: .bottom, animated: false)
                
            }
        }
    }
    
    // 图片或者音频点击方法回调
    override func routerEventWithName(_ eventName: String, userInfo: Dictionary<String, Any>, _ bingUI: UIView? = nil) {
      
          DebugPrint(eventName)
        DebugPrint(userInfo)
        DebugPrint(bingUI)
        if eventName == kMessageImageKey {
            if let item = userInfo[kMessageImageKey] as? CLChatImageItem{
                chatImageCellBubblePressed(item)
            }
        }else if eventName == kMessageVoiceKey{
            if let item = userInfo[kMessageVoiceKey] as? CLChatVoiceItem {
                if let cell = bingUI as? CLChatVoiceCell {
                     chatVoiceCellBubblePressed(item: item, cell: cell)
                }
            }
        }
    }
    
    // 点击图片预览
    func chatImageCellBubblePressed(_ model: CLChatImageItem){
        let list = tableViewHepler.rows.filter({ $0.cellClass() == CLChatImageCell.self })
        var imageUrl = Array<String>()
        for item in list {
            if let model = item as? CLChatImageItem{
                DebugPrint(model.imagePath)
                if let imagePath = model.imagePath{
                    imageUrl.append(imagePath)
                }
            }
        }
        let index = imageUrl.firstIndex(of: model.imagePath ?? "") ?? 0
        MCImagePreViewController.showPreImageView(viewController: self, urls: imageUrl, index: index)
    }
    
    //  点击语音
    func chatVoiceCellBubblePressed(item: CLChatVoiceItem,cell: CLChatVoiceCell){
        if cell == self {
            if player.isPlaying {
                player.pauseAudio()
            }else{
                player.playAudio()
            }
        }else{
            if player.isPlaying {
                player.pauseAudio()
            }
            player.selectCell = cell
            player.url = item.voiceUrl
            player.playAudio()
        }
    }
    
    
}


extension RSChatViewController {
    private func initUI() {
        view.backgroundColor = .init("#EEEEED")
        view.addSubview(tableView)
        view.addSubview(inputToolBar)
    }

    private func makeConstraints() {
        inputToolBar.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
        }
        tableView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.bottom.equalTo(inputToolBar.snp.top)
            make.height.equalToSuperview().offset(-(navigationController?.navigationBar.frame.height ?? 0.0) - statusBarHeight - inputToolBar.toolBarDefaultHeight)
        }
    }

    private func reloadData() {
        DispatchQueue.main.async { [weak self] in
            guard let weakself = self else { return }
            weakself.tableView.reloadData()
            if weakself.tableViewHepler.rows.count >= 1 {
                let item = max(weakself.tableViewHepler.rows.count - 1, 0)
                weakself.tableView.scrollToRow(at: IndexPath(item: item, section: 0), at: .bottom, animated: true)
            }
        }
    }
    
    
}

extension RSChatViewController {
    /// 添加提示语 不用加在数据库
    private func addTipsMessages(_ messages: [String]) {
        messages.forEach { text in
            let item = CLChatTipsItem()
            item.text = text
            tableViewHepler.rows.append(item)
        }
        reloadData()
    }

    // 添加文字
    private func addTextMessages(_ messages: String) {
        let rightItem = CLChatTextItem()
        rightItem.isFromMyself = true
        rightItem.text = messages
        tableViewHepler.rows.append(rightItem)
        
        
        let leftItem = CLChatTextItem()
        leftItem.isFromMyself = false
        leftItem.text = messages
        tableViewHepler.rows.append(leftItem)
        
        RSMessageViewModel.insertNewMessage(roomId, rightItem)
        RSMessageViewModel.insertNewMessage(roomId, leftItem)
        
        reloadData()
    }

    private func addImageMessages(_ messages: [(image: UIImage, asset: PHAsset)]) {
        messages.forEach { imageInfo in
            guard let previewImageData = imageInfo.image.pngData() else {
                return
            }
            let rightItem = CLChatImageItem()
            rightItem.imagePath = saveUploadImage(imageData: previewImageData, messageId: rightItem.messageId + "previewImage")
            rightItem.imageOriginalSize = CGSize(width: imageInfo.asset.pixelWidth, height: imageInfo.asset.pixelHeight)
            rightItem.isFromMyself = true
            tableViewHepler.rows.append(rightItem)
            RSMessageViewModel.insertNewMessage(roomId, rightItem)
//            let leftItem = CLChatImageItem()
//            leftItem.imagePath = saveUploadImage(imageData: previewImageData, messageId: leftItem.messageId + "previewImage")
//            leftItem.imageOriginalSize = CGSize(width: imageInfo.asset.pixelWidth, height: imageInfo.asset.pixelHeight)
//            leftItem.isFromMyself = false
//            tableViewHepler.rows.append(leftItem)
        }
        reloadData()
    }

    private func addVoiceMessages(duration: TimeInterval, path: String) {
        do {
            let item = CLChatVoiceItem()
            item.duration = duration
            item.voiceUrl = path
            tableViewHepler.rows.append(item)
            RSMessageViewModel.insertNewMessage(roomId, item)
        }
        do {
            let item = CLChatVoiceItem()
            item.isFromMyself = false
            item.duration = duration
            item.voiceUrl = path
            tableViewHepler.rows.append(item)
            RSMessageViewModel.insertNewMessage(roomId, item)
        }
        reloadData()
    }
}

extension RSChatViewController {
    func saveUploadImage(imageData: Data, messageId: String) -> String? {
        let path = imageUploadPath + "/\(messageId)"
        if !FileManager.default.fileExists(atPath: imageUploadPath) {
            try? FileManager.default.createDirectory(atPath: imageUploadPath, withIntermediateDirectories: true, attributes: nil)
        }
        if (imageData as NSData).write(toFile: path, atomically: true) {
            return path
        }
        return nil
    }
}

extension RSChatViewController {
    @objc func dismissKeyboard() {
        inputToolBar.dismissKeyboard()
    }
}

extension RSChatViewController: CLChatInputToolBarDelegate {
    func inputBarWillSendText(text: String) {
        addTextMessages(text)
    }

    func inputBarWillSendImage(images: [(image: UIImage, asset: PHAsset)]) {
        addImageMessages(images)
    }

    func inputBarFinishRecord(duration: TimeInterval, filePath: String) {
        addVoiceMessages(duration: duration, path: filePath)
    }
}

extension RSChatViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        guard let touchView = touch.view, !(touchView is UIButton) else {
            return false
        }
        if inputToolBar.bounds.contains(touch.location(in: inputToolBar)) {
            return false
        }
        return true
    }
}

